<template>
  <div class="content">
    <div class="form">
      <div class="btn-group">
        <el-button type="primary" @click="catchPic" :loading="catchPicLoading">抓图</el-button>
        <el-button type="primary" @click="remoteInspections()">远程点检</el-button>
      </div>
      <div class="btn-group">
        <el-button v-for="(item, index) in list" :key="index" @click="clickItem(index)">
          {{ item.text }}
        </el-button>
      </div>
      <iframe class="video" ref="myIframe" v-if="props.isShowIframe"></iframe>
    </div>
    <div class="form_image">
      <div class="imageBox">
        <span class="label">告警图片：</span>
        <div class="imageBox-item" v-for="(item, index) in picList" :key="index">
          <el-image style="width: 100px; height: 100px" :src="item" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
            :preview-src-list="picList" show-progress :initial-index="4" fit="cover" @show="changeVisible(false)"
            @close="changeVisible(true)">
          </el-image>
          <el-button type="danger" class="delete" :icon="Delete" circle @click="deletePic(index)" />
        </div>
      </div>
    </div>
    <el-drawer v-model="dialog" title="远程点检" :before-close="handleClose" direction="rtl" size="50%" class="demo-drawer"
      @open="changeVisible(false)" @close="changeVisible(true)">
      <!-- 动态生成的表单 -->
      <div v-for="(form, index) in formList" :key="index" class="demo-drawer__content">
        <el-form :model="form">
          <h3>点检问题{{ index + 1 }}</h3>
          <el-form-item label="点检现场图片" :label-width="formLabelWidth">
            <el-button type="primary" @click="selectImage(index)" style="width: 100px;">
              选择图片
            </el-button>
            <div class="imageBox-item" v-for="(item, indexImage) in form.picList" :key="indexImage">
              <el-image style="width: 100px; height: 100px" :src="item" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                :preview-src-list="form.picList" show-progress :initial-index="4" fit="cover">
              </el-image>
              <el-button type="danger" class="delete" style="width: 10px;height: 10px;" :icon="Delete" circle
                @click="deletePicForm(index, indexImage)" />
            </div>
          </el-form-item>
          <el-form-item label="点检问题类型" :label-width="formLabelWidth">
            <el-select v-model="form.problemTypeValue" placeholder="请选择问题类型" class="inputContent"
              @click="getTypeQueclassify(index)"></el-select>
          </el-form-item>
          <el-form-item label="点检意见" :label-width="formLabelWidth">
            <el-input v-model="form.opinion" autocomplete="off" class="inputContent" />
          </el-form-item>
          <el-form-item label="是否需要整改" :label-width="formLabelWidth">
            <el-select v-model="form.needRectify" class="inputContent">
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="整改人" :label-width="formLabelWidth">
            <el-select v-model="form.rectifier" placeholder="请选择整改人" class="inputContent"
              @click="getUser(index, false)"></el-select>
          </el-form-item>
          <!-- <el-form-item label="协办人" :label-width="formLabelWidth">
            <el-select v-model="form.organizer" placeholder="请选择协办人" class="inputContent"
              @click="getUser(index, true)"></el-select>
          </el-form-item> -->
          <el-form-item label="整改截止日期" :label-width="formLabelWidth">
            <el-date-picker v-model="form.deadlineTime" type="datetime" placeholder="请选择整改截止日期"
              value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
          <el-form-item label="是否集中运营" :label-width="formLabelWidth">
            <el-radio-group v-model="form.focusOperation">
              <el-radio :value="true">是</el-radio>
              <el-radio :value="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否现场巡查" :label-width="formLabelWidth">
            <el-radio-group v-model="form.isSitepatrol">
              <el-radio :value="true">是</el-radio>
              <el-radio :value="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="反馈日期" :label-width="formLabelWidth" v-if="!form.isSitepatrol"> 
            <el-date-picker v-model="form.feedbackDate" type="datetime" placeholder="请选择反馈日期"
            value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
          <el-form-item label="处置措施" :label-width="formLabelWidth" v-if="!form.isSitepatrol">
            <el-input v-model="form.disposalMeasures" autocomplete="off" class="inputContent" />
          </el-form-item>
          <el-form-item label="处置原因" :label-width="formLabelWidth" v-if="!form.isSitepatrol">
            <el-input v-model="form.disposalReason" autocomplete="off" class="inputContent" />
          </el-form-item>
          <el-form-item label="本次巡查总结" :label-width="formLabelWidth" v-if="!form.isSitepatrol">
            <el-input v-model="form.patrolSummary" autocomplete="off" class="inputContent" />
          </el-form-item>
        </el-form>
        <el-button type="text" class="delete-form-btn" @click="removeForm(index)">
          <el-icon :size="24">
            <Close />
          </el-icon>
        </el-button>
      </div>
      <el-button type="primary" @click="addForm">添加点检问题</el-button>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" :loading="loading" @click="onClick">
          {{ loading ? '正在提交 ...' : '提交' }}
        </el-button>
      </div>
    </el-drawer>

    <el-dialog class="type-dialog" v-model="typeDialogVisible" width="85%" :close-on-click-modal="false">
      <el-row :gutter="20">
        <el-col :span="6" style="height: 400px; border: 10; overflow: auto">
          <el-tree class="filter-tree" :data="treeData" :props="defaultProps" default-expand-all
            :expand-on-click-node="false" ref="tree" @node-click="handleNodeClick" />
        </el-col>
        <el-col :span="14">
          <div class="tool">
            <el-form :inline="true" :model="formInline" class="demo-form-inline" @submit.prevent>
              <el-form-item label="关键字">
                <el-input v-model="formInline.keyword" @keyup.enter="search" placeholder="名称或编码" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="search">查询</el-button>
              </el-form-item>
            </el-form>
          </div>
          <el-table :data="typeQueclassifyData" @selection-change="correctorSelectType" ref="multipleTable"
            height="350">
            <el-table-column label="选择" width="55">
              <template #default="scope">
                <el-radio v-model="tempSelectedCorrectorType" :label="scope.row" @click.stop>&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column property="fullname" label="长名称" />
            <el-table-column property="name" label="名称" />
            <el-table-column property="number" label="编码" />
            <el-table-column property="wens_classification" label="业务分类" :formatter="formatWensClassification" />
            <el-table-column property="wens_patrol_method" label="巡查方式" :formatter="formatWensPatrolMethod" />
          </el-table>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="typeDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmTypeQueclassify">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="选择人员" v-model="correctorDialogVisible" width="85%" :close-on-click-modal="false">
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="tool">
            <el-form :inline="true" class="demo-form-inline" @submit.prevent>
              <el-form-item label="关键字">
                <el-input @keydown.enter="enterEvent" v-model="correctorKeyword" ref="correctorKeywordRef"
                  placeholder="名字或手机号" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getUser(formIndex, flag)">查询</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table v-loading="corrector" :data="correctorDataList" @row-click="correctorSelectUser" height="450"
            ref="correctorMultipleTable">
            <el-table-column label="选择" width="55">
              <template #default="scope">
                <el-radio v-model="tempSelectedCorrectorUser" :label="scope.row" @click.stop>&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column property="id" label="用户id" width="100" />
            <el-table-column property="name" label="姓名" width="100" />
            <el-table-column property="mobile" label="手机号" width="200" />
            <el-table-column property="orgFullname" label="所属组织" width="600" />
            <el-table-column property="position" label="职务" />
          </el-table>

          <div class="pagewrap" style="margin-top: 50px">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="1"
              :page-sizes="[100, 200, 300, 400]" :page-size="100" layout="total, sizes, prev, pager, next, jumper"
              :total="correctorDataTotal" />
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="confirmCorrector">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片选择弹窗 -->
    <el-dialog v-model="showImageDialog" title="选择图片" width="70%">
      <div class="image-selection-container">
        <div v-for="(img, index) in picList" :key="index" class="selectable-image"
          :class="{ 'selected': isSelected(img) }" @click="toggleSelect(img)">
          <el-image :src="img" style="width: 100px; height: 100px" fit="cover">
          </el-image>
        </div>
      </div>
      <template #footer>
        <el-button @click="showImageDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmSelection">确认</el-button>
      </template>
    </el-dialog>

  </div>
</template>
<script setup>
import { ref, onMounted, reactive, nextTick, toRaw } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPatrolAlarmDetailInfo, uploadImage, getRolePermissions, getUserList, getTypeTree, getTypeList, savePatrolAlarmAndTask } from '@/api/api'
import { useRoute } from 'vue-router'
import { useBaseParamStore } from '@/stores/baseParams'
import { Delete, Close } from '@element-plus/icons-vue'

const baseParamStore = useBaseParamStore()
const route = useRoute();
const formData = ref({});
const list = ref([]);
const picList = ref([]);
const showImageDialog = ref(false);
const tempSelection = ref([]); // 临时选择的图片
const myIframe = ref(null);
// 任务中心获取派单权限接口
const hasPermission = ref(false);
const formIndex = ref(0);
const flag = ref(false);
const formLabelWidth = '100px';
const dialog = ref(false);
const loading = ref(false);
const catchPicLoading = ref(false);

const typeDialogVisible = ref(false);
const treeData = ref([]);
const typeQueclassifyData = ref([]);
const tempSelectedCorrectorUser = ref({});
const tempSelectedCorrectorType = ref({});

const correctorDialogVisible = ref(false);
const correctorKeyword = ref('');
const correctorMultipleTable = ref(null);
const corrector = ref(false);
const correctorDataList = ref([]);
const correctorDataTotal = ref(0);
const page = reactive({ size: 100, current: 1 });

const props = defineProps({ isShowIframe: { type: Boolean, default: true } });

// 定义表单数据结构
const formList = reactive([
  {
    farmer: decodeURIComponent(baseParamStore.baseParam.rearerId),
    orgId: route.query.orgId,
    userId: '',
    organizer: '',
    problemType: '',
    problemTypeValue: '',
    itemProblemType: '',
    eventType: '',
    itemProblemTypeName: '',
    eventTypeName: '',
    opinion: '',
    needRectify: '',
    rectifier: '',
    deadlineTime: '',
    focusOperation: true,
    isSitepatrol: true,
    feedbackDate: '',
    disposalMeasures: '',
    disposalReason: '',
    patrolSummary: '',
    picList: []
  }
]);

const defaultProps = reactive({ children: "children", label: "name" });
const formInline = reactive({ keyword: "", parentId: "" });

const formatWensClassification = (row) => {
  const map = { '0': '种猪', '1': '肉猪', '2': '种禽', '3': '肉禽' };
  return map[row.wens_classification];
};

const formatWensPatrolMethod = (row) => {
  const map = { '0': '常规巡查', '1': '精准巡查', '2': '临时巡查' };
  return map[row.wens_patrol_method];
};

const options = [
  { label: '实际测算猪群单头体重低于对应生长天龄目标体重(斤)', value: '1' },
  { label: '实际测算猪群单头体重低于对应累计耗料目标体重(斤)', value: '2' },
  { label: '实际日增重偏高标准日增重(斤)', value: '3' },
  { label: '累计耗料量偏离标准耗料(%)', value: '4' },
  { label: '料槽余料覆盖率(%)', value: '5' },
  { label: '料槽余料异常占比(%)', value: '6' },
  { label: '温度', value: '7' },
  { label: '湿度', value: '8' },
  { label: 'CO2', value: '9' },
  { label: '智能环控舒适度(待建)', value: '10' },
  { label: '猪群打堆比例', value: '11' },
  { label: '猪群集中在排泄区数量', value: '12' },
  { label: '猪群异常栏位占比(%)', value: '13' },
  { label: '巡查员远程验收是否达标', value: '14' },
  { label: '环境采样是否阳性', value: '15' },
  { label: 'AI点数记录与仔猪上市记录数差异头数', value: '16' },
  { label: 'AI点数记录与系统存栏数差异头数', value: '17' },
  { label: 'AI点数记录与肉猪回收单差异头数', value: '18' },
  { label: '上市尾猪存栏数(开栏销售标准天数外)', value: '19' },
  { label: '是否存在对应人员、物资的进出报备单记录', value: '20' },
  { label: '智能烘干消毒是否正常结束', value: '21' },
  { label: '智能浸泡消毒是否正常结束', value: '22' },
];
const labelToValueMap = reactive({});

const itemMap = reactive({
  '肉猪空栏洗消': 1,
  '肉猪分栏': 2,
  '肉猪健康-差弱猪护理': 3,
  '肉猪生长监测': 4,
  '生物资产端到端-进苗验收': 5,
  '生物安全-红区管理': 6,
  '生物资产端到端-死淘申报': 7,
  '肉猪饲喂': 8,
  '肉猪环控': 9,
  '生物资产端到端-过程盘点': 10,
  '生物资产端到端-上市盘点': 11,
  '生物资产端到端-上市尾猪处理': 12
});

const eventMap = reactive({
  '空栏巡查': 1,
  '肉猪饲养巡查': 2,
  '生物资产端到端': 3,
  '生物安全巡查': 4,
  '肉猪健康巡查': 5
});

onMounted(async () => {
  options.forEach(item => {
    labelToValueMap[item.label] = item.value;
  });
  fetchPatrolAlarmDetailInfo();
  // 接收监听
  window.addEventListener('message', async (event) => {
    if (!event.data) {
      return
    }
    if (event.data.code == '100') {
      // 接收返回的可播放的列表
      list.value = event.data.msg;
    } else if (event.data.code == '101') {
      const base64 = `data:image/*;base64,${event.data.msg}`;
      // 添加水印
      const watermarkedBase64 = await addWatermark(base64);
      catchPicLoading.value = false;
      const blob = base64ToFile(watermarkedBase64, 'test.jpg');
      const res = await uploadImage(blob);
      picList.value.push(`${import.meta.env.VITE_IMG_URL}${res.data[0]}`);
    } else if (event.data.code == '003') {
      ElMessage({ message: event.data.msg, type: 'warning' });
    } else {
      console.log(event.data.msg);
    }
  });
});

// 选择图片
const selectImage = (index) => {
  showImageDialog.value = true;
  formIndex.value = index;
};

// 切换图片选择状态
const toggleSelect = (img) => {
  const index = tempSelection.value.indexOf(img);
  if (index === -1) {
    tempSelection.value.push(img);
  } else {
    tempSelection.value.splice(index, 1);
  }
};

// 检查图片是否被选中
const isSelected = (img) => {
  return tempSelection.value.includes(img);
};

// 确认选择
const confirmSelection = () => {
  formList[formIndex.value].picList = [...tempSelection.value];
  tempSelection.value = [];
  showImageDialog.value = false;
};

// 删除图片
const deletePicForm = (index, indexImage) => {
  formList[index].picList.splice(indexImage, 1);
};

const remoteInspections = () => {
  dialog.value = true;
}

const getTreeType = async (index) => {
  try {
    const res = await getTypeTree();
    if (res && res.data) {
      treeData.value = res.data;
      formIndex.value = index;
    }
  } catch (error) {
    console.error('获取类型树失败:', error);
  }
};

const getListType = async () => {
  try {
    const res = await getTypeList(formInline);
    if (res && res.data) {
      typeQueclassifyData.value = res.data;
    }
  } catch (error) {
    console.error('获取类型列表失败:', error);
  }
};

const getTypeQueclassify = (index) => {
  typeDialogVisible.value = true;
  getTreeType(index);
};

const handleNodeClick = (nodeData) => {
  formInline.parentId = nodeData.id;
  search();
};

const search = () => {
  getListType();
};

const correctorSelectType = (row) => {
  tempSelectedCorrectorType.value = row;
};

const getUser = async (index, tag) => {
  correctorDialogVisible.value = true;
  corrector.value = true;
  const requestData = {
    keyword: correctorKeyword.value,
    partOrg: true,
    orgId: route.query.orgId
  };
  try {
    const res = await getUserList(requestData);
    if (res && res.data) {
      correctorDataList.value = res.data.list;
      correctorDataTotal.value = res.data.total;
      nextTick(() => {
        if (correctorMultipleTable.value?.bodyWrapper) {
          correctorMultipleTable.value.bodyWrapper.scrollTop = 0;
        }
      });
      formIndex.value = index;
      flag.value = tag;
    }
    corrector.value = false;
  } catch (error) {
    corrector.value = false;
    console.error('获取用户列表失败:', error);
  }
};

const correctorSelectUser = (row) => {
  tempSelectedCorrectorUser.value = row;
};

const confirmTypeQueclassify = () => {
  formList[formIndex.value].problemTypeValue = tempSelectedCorrectorType.value.name;
  formList[formIndex.value].problemType = labelToValueMap[tempSelectedCorrectorType.value.name] || '';
  const itemArray = tempSelectedCorrectorType.value.fullname.split('.');
  if (itemArray.length >= 2) {
    formList[formIndex.value].itemProblemType = itemMap[itemArray[1]] || '';
    formList[formIndex.value].eventType = eventMap[itemArray[0]] || '';
    formList[formIndex.value].itemProblemTypeName = itemArray[1];
    formList[formIndex.value].eventTypeName = itemArray[0];
  }
  typeDialogVisible.value = false;
  formInline.keyword = "";
  formInline.parentId = "";
};

const enterEvent = () => {
  getUser(formIndex.value, flag.value);
};

// 分页大小变化处理
const handleSizeChange = (val) => {
  page.size = val;
  page.current = 1;
  getUser(formIndex.value, flag.value);
};

// 当前页变化处理
const handleCurrentChange = (val) => {
  page.current = val;
  getUser(formIndex.value, flag.value);
};

const handleCancel = () => {
  correctorDialogVisible.value = false;
  correctorKeyword.value = '';
};

const confirmCorrector = () => {
  // 确认选择逻辑
  if (flag.value) {
    formList[formIndex.value].organizer = tempSelectedCorrectorUser.value.name;
  } else {
    formList[formIndex.value].rectifier = tempSelectedCorrectorUser.value.name;
  }
  formList[formIndex.value].userId = tempSelectedCorrectorUser.value.id;
  correctorDialogVisible.value = false;
  correctorKeyword.value = "";
};

const catchPic = () => {
  // if (picList.value.length == 3) {
  //   ElMessage({ message: '最多抓取3张图片', type: 'warning' });
  //   return;
  // }
  catchPicLoading.value = true;
  myIframe.value.contentWindow.postMessage({ handle: 'catchPic' }, '*');
}

const clickItem = (index) => {
  // 打开对应视频
  myIframe.value.contentWindow.postMessage({ handle: 'playVideo', data: index }, '*');
}

const changeVisible = (flag) => {
  myIframe.value.contentWindow.postMessage({ handle: 'changeVisible', data: flag }, '*');
}

const deletePic = (index) => {
  picList.value.splice(index, 1);
}

// 获取告警详情
const fetchPatrolAlarmDetailInfo = async () => {
  try {
    const res = await getPatrolAlarmDetailInfo({ fid: route.query.fid });
    if (res && res.data) {
      formData.value = res.data;
      formData.value.patrolConditions = res.data['patrolSpot'];
      fetchRolePermissions();
      // 打开视频
      showVideo();
    }
  } catch (error) {
    console.error('获取获取告警详情信息失败:', error);
  }
}

const fetchRolePermissions = async () => {
  try {
    const res = await getRolePermissions({
      userId: route.query.userId,
      userRole: 'DigitalPatrolAdmin',
      orgId: route.query.orgId
    });
    if (res.status) {
      hasPermission.value = res.data;
    }
  } catch (error) {
    console.error('获取预分配人员失败:', error.message); // 更详细的错误信息
  }
}

const showVideo = () => {
  let rect = myIframe.value.getBoundingClientRect();
  // 大华 测试调用需要加上 &access_token=xxx ，正式：https://cq.wens.com.cn//isv/wens/smartb/smartbAiVideo/base.html#/
  myIframe.value.src = `https://t-mall.wens.com.cn//isv/wens/smartb/smartbAiVideo/base.html#/DigtalSpaceVideoPlayerForIframe?orgId=${route.query.orgId}&farmerId=${formData.value.cqRearerId}&iframeFixLeftOffset=${rect.left + window.scrollX}&iframeFixTopOffset=${rect.top + window.scrollY}`;
}

// 添加水印
const addWatermark = async (base64Image) => {
  const img = new Image();
  img.src = base64Image;
  await new Promise((resolve) => (img.onload = resolve));
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  canvas.width = img.width;
  canvas.height = img.height;
  // 绘制原始图片
  ctx.drawImage(img, 0, 0);
  // 添加多行水印文字（右下角）
  ctx.fillStyle = 'red'; // 水印颜色
  ctx.font = '20px Arial';
  ctx.textAlign = 'right';
  ctx.textBaseline = 'bottom';
  const watermarkLines = [
    `养户:${formData.value.rearerName}`,
    `群号:${formData.value.flockNumber}`,
    `时间:${getCurrentDate()}`,
    `饲喂形态:''`,
    `病弱猪类型:''`
  ];
  const lineHeight = 25; // 行高
  const startX = canvas.width - 20; // 右侧留白
  let startY = canvas.height - 20; // 底部留白

  watermarkLines.forEach((line) => {
    ctx.fillText(line, startX, startY);
    startY -= lineHeight;
  })
  return canvas.toDataURL('image/png');
}

// 生成当前时间
const getCurrentDate = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const formattedDate = `${year}-${month}-${day}`;
  return formattedDate;
}

function base64ToFile(base64Image, filename) {
  // 步骤1: 去除 Base64 的 data URL 前缀
  const base64Data = base64Image.replace(/^data:image\/\w+;base64,/, '');
  // 步骤2: 解码 Base64 数据为二进制字符串
  const binaryString = atob(base64Data);
  // 步骤3: 转换为 Uint8Array
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  // 步骤4: 创建 Blob 对象
  const blob = new Blob([bytes.buffer], { type: 'image/jpeg' }); // 根据实际图片类型修改 MIME 类型
  // 步骤5: 创建 File 对象
  const file = new File([blob], filename, { type: 'image/jpeg' });
  return file;
}

// 提交按钮
const onClick = async () => {
  loading.value = true;
  try {
    const rawFormList = toRaw(formList).map(item => ({ ...item }));
    console.log(rawFormList);
    const res = await savePatrolAlarmAndTask({
      paramsList: rawFormList
    })
    if (res && res.status) {
      ElMessage({ message: res.data, type: 'success' })
    } else {
      ElMessage({ message: res.message, type: 'error' })
    }
    loading.value = false;
    dialog.value = false;
    formList.length = 0;
  } catch (error) {
    ElMessage({ message: '保存远程点检内容失败', type: 'error' });
    loading.value = false;
    formList.length = 0;
  }
}

const handleClose = (done) => {
  ElMessageBox.confirm('表单还未提交,是否关闭表单?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }).then(() => {
    loading.value = false;
    dialog.value = false;
    done();
  }).catch(() => {
    // catch error
  })
}

const cancelForm = () => {
  loading.value = false;
  dialog.value = false;
}

// 添加表单
function addForm() {
  formList.push({
    farmer: decodeURIComponent(baseParamStore.baseParam.rearerId),
    orgId: route.query.orgId,
    userId: '',
    organizer: '',
    problemType: '',
    problemTypeValue: '',
    itemProblemType: '',
    eventType: '',
    itemProblemTypeName: '',
    eventTypeName: '',
    opinion: '',
    needRectify: '',
    rectifier: '',
    deadlineTime: '',
    picList: []
  });
}

// 删除指定索引的表单
function removeForm(index) {
  formList.splice(index, 1);
}
</script>

<style scoped lang="scss">
.content {
  width: 100%;
  height: 100%;
  flex-direction: column;
  display: flex;
  justify-content: center;
  align-items: center;
}

.form {
  width: 100%;
  height: 100vh;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

.btn-group {
  width: 500px;
  margin-bottom: 5px;
}

.video {
  width: 80%;
  height: 70vh;
}

.imageBox {
  width: 1400px;
  overflow-x: auto;
  display: flex;
  position: relative;
  align-items: flex-start;

  .delete {
    width: 10px;
    height: 10px;
  }

  &-item {
    margin-right: 10px;
  }
}

.image-selection-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.selectable-image {
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s;
}

.selectable-image.selected {
  border: 2px solid red;
}

.selectable-image:hover {
  transform: scale(1.05);
}

.form_image {
  width: 100%;
  height: 28vh;
  flex-direction: column;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  text-align: center;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

.demo-drawer__content {
  position: relative;
  margin-bottom: 30px;
}

.delete-form-btn {
  position: absolute;
  top: 0;
  right: 10px;
  color: #ff4d4f;

  &:hover {
    color: #ff7875;
  }
}

.label {
  font-size: large;
}

.demo-drawer__footer {
  display: flex;
  justify-content: center;
  align-items: center;
}

.inputContent {
  width: 300px;
  height: 35px;
}

:deep(.el-button) {
  width: 150px;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
}

.tool {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  align-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>
